<template>
	<view class="module-list-page">
		<view class="module-layout">
			<view class="header card">
				<view class="container">
					<text>{{ params.title }}</text>
				</view>
			</view>
			<view class="main" v-if="modulesList.length">
				<view id="leftBox" ref="scroll-box" class="module-scroll-box card">
					<scroll-view scroll-y="true" style="height:100%;transition: 0.5s;" :scroll-top="scrollTop"
						scroll-with-animation>
						<view class="item card" v-for="(moduleItem, index) in modulesList" :key="moduleItem.value"
							:class="index == currentIndex ? 'active' : ''" @click="selectItem(moduleItem, index)">
							<ModuleCardItem class="card" :row-data="moduleItem">
								<template v-slot:icon="{ data }">
									<view class="icon" :style="{ color: modulesColor(moduleItem.value) }">
										<!-- <text
											v-if="vuex_config.isConnected && ['10', '11', '12'].includes(moduleItem.value)"
											class="iconfont" @click.stop="showQr(moduleItem)">&#xe642;</text>
										<text v-else-if="['13'].includes(moduleItem.value)" class="iconfont"
											@click.stop="toVideoTimeAxis(moduleItem)">
											&#xe69a;
										</text> -->
									</view>
									<view class="num">{{ moduleItem.fileNum || 0 }}</view>
								</template>
							</ModuleCardItem>
						</view>
					</scroll-view>
				</view>
				<view class="module-list-box">
					<scroll-view scroll-y="true" style="height:100%;transition: 0.5s;" :scroll-top="mainScrollTop"
						@scroll="scroll" scroll-with-animation>
						<view class="content">
							<ScrollingRightList ref="rightScrollList" :list="modulesList" :data="cardList"
								:archivesId="archivesId" @getModuleList="Refresh" />
						</view>
					</scroll-view>
				</view>
			</view>
			<u-empty v-else text="暂无数据" :icon-size="200" mode="list"></u-empty>
		</view>
		<u-popup v-model="videoPopupObj.show" mode="right">
			<view class="video-group">
				<view v-if="videoPopupObj.list.length">
					<view class="padding_20 font_weight_bold font_size_16">
						<view>语音播放</view>
					</view>
					<view v-for="(video, index) in videoPopupObj.list" :key="index">
						<audio style="text-align: left" :src="video.value" :name="video.label" controls></audio>
					</view>
				</view>
				<u-empty v-else text="暂无录音" mode="list" font-size="36"></u-empty>
			</view>
		</u-popup>
		<u-modal v-model="delObj.show" :content="delObj.content" show-cancel-button @confirm="delConfirm"></u-modal>
		<u-mask :show="qrShow">
			<view class="warp" style="height: 100%;" @click="cancelQr">
				<view style="height: 100%;" flex="cross:center main:center dir:top" class="rect">
					<!-- <uqrcode class="margin_bottom_10" :size="256" :margin="10" ref="uQRCode" @tap.stop :text="qrcodeText"
						@complete="qrComplete" /> -->
					<view class="color_fff font_size_24">请扫描二维码</view>
				</view>
			</view>
		</u-mask>
		<u-modal v-model="toAppModule.show" :content="toAppModule.content" :show-cancel-button="true"
			@confirm="appModuleConfirm"></u-modal>
		<u-modal v-model="isAppModule.show" :content="isAppModule.content" :show-cancel-button="true"
			@confirm="isAppModuleConfirm"></u-modal>
		<u-modal v-model="downloadModel.show" :title-style="{ color: 'red' }" :show-confirm-button="false"
			:show-cancel-button="true" @cancel="downloadModelCancel">
			<view class="slot-content">
				<view>{{ downloadModel.content }}</view>
				<!-- <rich-text :nodes="downloadModel.content"></rich-text> -->
			</view>
		</u-modal>
	</view>
</template>

<script>
import { mapModulesColor, mapModulesTextAvatar } from '@/const';
import { getLocalFile } from '@/static/common/js/util';
import ModuleCardItem from './components/ModuleCardItem.vue'
import ScrollingRightList from './components/ScrollingRightList.vue'
import { getModulesListFromArchive, getEvidenceChainListFromArchive } from '@/common/environmentalApi/index.js'
export default {
	components: {
		ModuleCardItem,
		ScrollingRightList
	},
	data() {
		return {
			archivesId: null,
			modulesList: [],
			currentIndex: 0,
			cardList: {},
			dictId: 1,
			archivesType: '',
			videoPopupObj: {
				show: false,
				list: []
			},
			delObj: {
				show: false,
				content: '请再次确认是否删除？',
				index: null,
				collapseIndex: null,
				moduleItem: null
			},
			qrShow: false,
			qrcodeText: '',
			scrollTop: 0,
			init: false,
			webViewShow: false,
			noAsyncPopup: {
				index: null
			},
			toAppModule: {
				show: false,
				content: ''
			},
			isAppModule: {
				show: false,
				content: '检测到应用未安装，是否自动为您安装应用'
			},
			params: {},
			_prg: 0,
			_showLoading: null,
			_dtask: null,
			downloadModel: {
				show: false,
				content: ''
			},
			mainScrollTop: '0',
			scrollTimer: null
		};
	},
	computed: {
		modulesColor() {
			return val => {
				return mapModulesColor[val];
			};
		},
		cardAvatar() {
			return value => {
				return mapModulesTextAvatar[value];
			};
		}
	},
	onLoad(params) {
		console.log(params);
		uni.showLoading({
			title: '数据加载中',
			mask: true
		})
		this.currentIndex = params.currentIndex;
		this.archivesId = params.archivesId;
		this.dictId = parseInt(params.dictId) || 1;
		this.archivesType = params.archivesType;
		this.params = params;
		// #ifdef APP-PLUS
		getModulesListFromArchive(this.params).then(list => {
			console.log(list);
			this.modulesList = list;
			this.$nextTick(() => {
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this).select(
						'#leftBox .active');
					query.boundingClientRect(data => {
						//目标节点、也可以是最外层的父级节点
						this.scrollTop = (data?.top - data?.height - 10) || 0;
						this.init = false;
						this.selectItem({
							name: ''
						}, this.currentIndex)
					}).exec();
				}, 1000)

			});
		}).catch((err) => {
			console.log(err);
			uni.hideLoading()
		})
		getEvidenceChainListFromArchive(this.params).then(list => {
			let rightData = {}
			list.forEach(item => {
				rightData[item.dictId] = item.mapList
			})
			console.log(rightData);
			this.cardList = rightData
			uni.hideLoading()
		}).catch(()=>{
			uni.hideLoading()
		})
		// #endif
	},
	onReady() {

	},
	onShow() {
	},
	onUnload() {
		plus.downloader.clear();
	},
	onNavigationBarButtonTap(e) {
		uni.navigateBack({ delta: 1 })
	},
	methods: {
		Refresh() {
			getModulesListFromArchive(this.params).then(list => {
				this.modulesList = list;
			}).catch((err) => {
				console.log(err);
			})
			getEvidenceChainListFromArchive(this.params).then(list => {
				let rightData = {}
				list.forEach(item => {
					rightData[item.dictId] = item.mapList
				})
				this.cardList = rightData
			})
		},
		selectItem(item, index) {
			this.currentIndex = index;
			if (index == 0) {
				this.mainScrollTop = 0
				return false
			}
			const query = uni.createSelectorQuery().in(this)
			let id = '#module' + index
			query.select(id).boundingClientRect((res) => {
				uni.createSelectorQuery().select('.content').boundingClientRect((data) => {
					if (!res || !data) return
					this.mainScrollTop = res?.top - data?.top - 10
				}).exec()
			}).exec()
		},
		async uploadImg(path) {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: this.vuex_config.baseUrl + '/common/upload', //仅为示例，非真实的接口地址
					filePath: 'file://' + path, // 获取到的路径 要加 file://
					header: {
						Authorization: this.vuex_token
					},
					name: 'file',
					success(uploadFileRes) {
						let fileResData = JSON.parse(uploadFileRes.data);
						if (uploadFileRes.statusCode == 200 && fileResData.code == 200) {
							resolve(fileResData.data);
						}
					},
					fail: e => { }
				});
			});
		},
		appModuleConfirm() {
			let name = this.toAppModule.type == 'magicplan' ? 'com.sensopia.magicplan' : 'com.newskyer.draw';
			// #ifdef APP-PLUS
			const isApp = plus.runtime.isApplicationExist({
				pname: name
			});

			if (isApp) {
				let sendData = {
					email: 'chenlengsu_it@163.com',
					password: 'password',
					mode: 'password'
				};
				plus.runtime.launchApplication({
					// pname: "com.sensopia.magicplan",
					// pname: "com.jideos.jnotes",
					pname: name,
					extra: sendData
				},
					e => { }
				);
			} else {
				this.isAppModule.show = true;
			}
			// #endif
		},
		isAppModuleConfirm() {
			let downloadApkUrl =
				this.toAppModule.type == 'magicplan' ?
					'https://cxdy-enforce.oss-cn-hangzhou.aliyuncs.com/softwares/cxdy_hd_sketch_magicplan.apk' :
					'https://cxdy-enforce.oss-cn-hangzhou.aliyuncs.com/softwares/cxdy_hd_sketch_xiangzuo.apk';
			this._dtask = plus.downloader.createDownload(downloadApkUrl, {}, function (d, status) {
				// 下载完成
				if (status == 200) {
					plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function (
						error) {
						uni.showToast({
							title: '安装失败',
							duration: 1500
						});
					});
				} else {
					uni.showToast({
						title: '更新失败',
						duration: 1500
					});
				}
			});
			// dtask.start();
			try {
				this._dtask.start(); // 开启下载的任务
				this._prg = 0;
				// this._showLoading = plus.nativeUI.showWaiting("正在下载"); //创建一个showWaiting对象
				this.downloadModel.show = true;
				this.downloadModel.content = '正在下载';
				this._dtask.addEventListener('statechanged', this.stateChanged, false);
			} catch (err) {
				plus.nativeUI.closeWaiting();
			}
		},
		stateChanged(task, status) {
			// 给下载任务设置一个监听 并根据状态  做操作
			switch (task.state) {
				case 1:
					// this._showLoading.setTitle("正在下载");
					this.downloadModel.content = '正在下载';
					break;
				case 2:
					// this._showLoading.setTitle("已连接到服务器");
					this.downloadModel.content = '已连接到服务器';
					break;
				case 3:
					this._prg = parseInt((parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100);
					// this._showLoading.setTitle("  正在下载" + this._prg + "%  ");
					this.downloadModel.content = '正在下载' + this._prg + '% ';
					break;
				case 4:
					plus.nativeUI.closeWaiting();
					this.downloadModel.show = false;
					//下载完成
					break;
			}
		},
		downloadModelCancel() {
			plus.downloader.clear();
		},
		scroll(e) {
			clearTimeout(this.scrollTimer)
			this.scrollTimer = setTimeout(() => {
				this.mainScrollTop = e.detail.scrollTop
			}, 200)
		},
		synchronization(item, index, path, typeName) {
			// this.noAsyncPopup.show = true
			this.noAsyncPopup.index = index;
			getLocalFile(path, typeName).then(files => {
				let data = files.map(item => this.uploadImg(item.fullPath));
				Promise.all(data).then(res => {
					let {
						fireName,
						address
					} = this.vuex_archives;
					let fileArr = res.map(obj => {
						return {
							...obj,
							form: {
								name: obj.name,
								planOrg: '',
								planPerson: this.vuex_user.nickName,
								fireOrg: fireName,
								address: address,
								doPlanTime: new Date().getTime(),
								creatTime: new Date()
							}
						};
					});
					this.editFun(fileArr);
				});
			});
		},
		editFun(fileArr) {
			let list = this.cardList;
			// list[this.noAsyncPopup.index].imgFileList.push(...fileArr)
			list[this.noAsyncPopup.index].imgFileList = fileArr;
			this.$u.api.record
				.edit(this.dictId, {
					noticeId: this.currentItem.noticeId,
					jsonStr: JSON.stringify(list),
					handleType: 2,
					archivesId: this.archivesId
				})
				.then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				});
		},
		onShowRight(record) {
			let arr = [];
			let list = record.videoFileList.forEach(imgFile => {
				// arr.push(...imgFile.form.studio);
				arr.push(imgFile.form);
			});
			this.videoPopupObj.list = arr;
			this.videoPopupObj.show = true;
		},
		delConfirm() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});

			let list = this.cardList[this.delObj.moduleItem.dictId];

			list.splice(this.delObj.index, 1);
			this.$u.api.record
				.edit(this.delObj.moduleItem.dictId, {
					noticeId: this.delObj.moduleItem.noticeId,
					jsonStr: JSON.stringify(list),
					handleType: 3,
					archivesId: this.archivesId
				})
				.then(res => {
					if (res.code == 200) {
						this.$emit('getModuleList')
					}
					uni.hideLoading();
					uni.showToast({
						title: res.msg
					});
				})
				.catch(() => {
					uni.hideLoading();
				});
		},
		toVideoTimeAxis(item) {
			console.log('item: ', item)
			let url = `${this.vuex_config.H5baseUrl}/videolist?token=${this.vuex_token}&noticeId=${item.noticeId}`
			// console.log(url);
			uni.navigateTo({
				url: `/pagesH5/videolist/index?noticeId=${item.noticeId}&title='视频预览'`
			})
		},
		showQr(item) {
			let path = item.dictId == '10' ? 'loss' : 'add';
			if (this.qrcodeText !=
				`${this.vuex_config.H5baseUrl}/${path}?&token=${this.vuex_token}&noticeId=${item.noticeId}`) {
				uni.showLoading({
					title: '二维码加载中'
				});
			}
			this.qrShow = true;
			console.log(`${this.vuex_config.H5baseUrl}/${path}?&token=${this.vuex_token}&noticeId=${item.noticeId}`);
			this.qrcodeText =
				`${this.vuex_config.H5baseUrl}/${path}?&token=${this.vuex_token}&noticeId=${item.noticeId}`;
		},
		qrComplete(e) {
			uni.hideLoading();
		},
		cancelQr() {
			uni.hideLoading();
			this.qrShow = false;
		}
	}
};
</script>

<style lang="scss" scoped>
.module-list-page {
	--header-height: 100%;

	.module-layout {
		height: 100%;
		padding: 32rpx;
		display: flex;
		flex-direction: column;
		height: 100vh;
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif  */

		.header {
			flex: 0 0 auto;
			overflow: hidden;
			// height: var(--header-height);
			padding: 32rpx 32rpx;
			color: $u-content-color;
			font-size: 36rpx;
			font-weight: bold;
			margin-bottom: 32rpx;
		}

		.main {
			flex: 1;
			display: flex;
			overflow: hidden;
		}
	}

	.module-scroll-box {
		flex: 1;
		flex: 0 0 250px;
		// width: 360rpx;
		overflow-y: auto;
		padding: 38rpx 32rpx;

		.item {
			margin-top: 28rpx;
			width: 100%;
			background-color: #fff;

			&:first-child {
				margin-top: 0;
			}

			&.active {
				background-color: #d2e9ff;
			}


			.icon {
				align-self: flex-end;

				text {
					font-size: 40rpx;
				}
			}

			.num {
				font-size: 48rpx;
			}


		}

		// }
	}

	.module-list-box {
		flex: 3;

		.content {
			padding-left: 32rpx;
			// padding: 40rpx 30rpx;
			// justify-content: space-between;

			.card {
				width: 33.33333333333333%;
				height: 320rpx;
				margin-bottom: 32rpx;
				padding: 0 18rpx;

				.add {
					height: 100%;
					border: 2rpx dashed $u-border-color;
					color: $u-content-color;
					border-radius: 4rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 32rpx;
				}

				.wrap {
					background-color: $u-card-bg-color;
					border-color: #00000017;
					box-shadow: 0 2px 8px #00000017;

					.body {
						width: 100%;
						height: 240rpx;
						display: flex;
						padding: 20rpx;
						position: relative;

						.avatar {
							display: flex;
							align-items: center;
							justify-content: center;
							min-width: 96rpx;
							height: 96rpx;
							overflow: hidden;
							margin-right: 24rpx;
							font-size: 46rpx;
							border-radius: 50%;
							color: #ffffff;
							opacity: 0.5;
						}

						.detail {
							.title {
								max-width: 300rpx;
								color: $u-content-color;
								margin-bottom: 24rpx;
								overflow: hidden; //超出的文本隐藏
								text-overflow: ellipsis; //溢出用省略号显示
								white-space: nowrap; //溢出不换行
							}

							.info {
								color: $u-light-color;
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 3;
								overflow: hidden;
								word-wrap: break-word;
								word-break: break-all;
							}

							.tag {
								position: absolute;
								right: 0;
								top: 0;
								font-size: 12rpx;
								color: #ffffff;
								padding: 4rpx 8rpx;
							}
						}
					}

					.menu {
						display: flex;
						align-items: center;
						justify-content: space-around;
						height: 80rpx;
						background: #f7f9fa;
						text-align: center;

						&>view {
							width: 50%;
							height: 100%;
							display: flex;
							align-items: center;
							justify-content: center;

							&.recording {
								.tips {
									border-radius: 50%;
									background-color: #d2e9ff;
									font-size: 16rpx;
									width: 20rpx;
									height: 20rpx;
								}
							}

							&.remove {
								color: $type-error;
								// background-color: $type-error;
							}
						}
					}
				}
			}
		}
	}

	.video-group {
		min-width: 640rpx;
		height: 100vh;
	}

	.noAsync-box {
		padding: 40rpx;

		uni-button {
			margin-bottom: 20rpx;
		}
	}
}

::v-deep .module-scroll-box {
	.uni-scroll-view-content {
		padding-top: 10rpx;

	}

	&#leftBox {
		.item {
			&.active {
				.module-item-card {
					.wrap {
						border-left-width: 12rpx;
						border-left-style: solid;
					}
				}
			}
		}
	}
}

.slot-content {
	text-align: center;

	view {
		padding: 40rpx 0;
	}
}
</style>